import requests
import json
import base64
import hashlib


class QywxBot(object):

    def __init__(self, webhook):
        self.webhook = webhook

    def send_msg(self, content):
        """艾特全部，并发送指定信息"""
        data = {
            "msgtype": "text",
            "text": {
                "content": content,
            }
        }
        r = requests.post(self.webhook, json=data, headers={'Content-Type': 'application/json'})
        print(r.reason)

    def send_img(self, img_add):
        with open(img_add, 'rb') as file:  # 转换图片成base64格式
            data = file.read()
            encodestr = base64.b64encode(data)
            image_data = str(encodestr, 'utf-8')

        with open(img_add, 'rb') as file:  # 图片的MD5值
            md = hashlib.md5()
            md.update(file.read())
            image_md5 = md.hexdigest()

        headers = {"Content-Type": "application/json"}
        data = {
            "msgtype": "image",
            "image": {
                "base64": image_data,
                "md5": image_md5
            }
        }
        result = requests.post(self.webhook, headers=headers, json=data)
        return result

    def send_makedown(self):
        headers = {"Content-Type": "application/json"}
        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": "今日收益<font color=\"warning\">123456元</font>。\n>"
                           "品种1: < font color =\"comment\">123元</font>\n"
                           "品种2: < font color =\"comment\">117元</font>\n"
                           "品种3: < font color =\"comment\">1512元</font>"
            }
        }
        result = requests.post(self.webhook, headers=headers, json=data)
        return result


if __name__ == '__main__':
    bot = QywxBot("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6cb4e91f-b781-48b0-b5b3-275240d9fbce")
    bot.send_msg("hello world!")
    #bot.send_img("D:\\img.jpg")
    #bot.send_makedown()
